package wall

import (
	"encoding/binary"
	"net"
	"strings"
	"time"

	"gitee.com/haodreams/libs/sock"

	"gitee.com/haodreams/libs/config"
)

// Recv .
type Recv struct {
	ackChar       byte //确认字符
	listenAddress string
	timeout       time.Duration
}

// NewRecv .
func NewRecv(conf config.Configer) *Recv {
	s := new(Recv)
	s.listenAddress = conf.DefaultString("local_address", ":13000")
	if !strings.HasPrefix(s.listenAddress, ":") {
		s.listenAddress = ":" + s.listenAddress
	}
	s.ackChar = byte(conf.DefaultInt("ack_char", 0))
	s.timeout = time.Duration(conf.DefaultInt("timeout", 30)) * time.Second

	return s
}

// Read .
func (m *Recv) Read(conn *net.TCPConn) (data []byte, err error) {
	data = make([]byte, 2)
	conn.SetReadDeadline(time.Now().Add(m.timeout))
	_, err = sock.Read(conn, data)
	if err != nil {
		return
	}
	l := binary.BigEndian.Uint16(data)
	isLz4Frame := l&MaskLz4 == MaskLz4
	l &= MaskNone
	data = make([]byte, l)
	_, err = sock.Read(conn, data)
	if err != nil {
		return
	}

	if isLz4Frame {
		data, err = Lz4Decode(data)
		if err != nil {
			return
		}
	}

	_, err = conn.Write([]byte{m.ackChar})
	return
}
